package com.chuanjiabao.wisdom.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.CycleInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.model.GeneratePresignedUrlRequest;
import com.chuanjiabao.wisdom.MainActivity;
import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.adapter.MonthAdapter;
import com.chuanjiabao.wisdom.application.FApplication;
import com.chuanjiabao.wisdom.bean.AuthCallbackBean;
import com.chuanjiabao.wisdom.bean.FamilyFileTotalBean;
import com.chuanjiabao.wisdom.bean.FamilyResCallbackBean;
import com.chuanjiabao.wisdom.bean.ImageBean;
import com.chuanjiabao.wisdom.bean.ReasionInfoCallbackBean;
import com.chuanjiabao.wisdom.databinding.FragmentSecondBinding;
import com.chuanjiabao.wisdom.listener.OnBHClickListener;
import com.chuanjiabao.wisdom.listener.RxObserver;
import com.chuanjiabao.wisdom.ui.activity.CreateSecretInputPwdActivity;
import com.chuanjiabao.wisdom.ui.activity.SecretResActivity;
import com.chuanjiabao.wisdom.ui.activity.ShootActivity;
import com.chuanjiabao.wisdom.ui.activity.UpdateTextActivity;
import com.chuanjiabao.wisdom.util.BHThreadPool;
import com.chuanjiabao.wisdom.util.DropPopWindowUtils;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.SpResourceUtil;
import com.chuanjiabao.wisdom.util.SpUtils;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.TimeHelper;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.chuanjiabao.wisdom.util.dialog.CreateSecretAlbumDialog;
import com.chuanjiabao.wisdom.util.dialog.ThirdSelectDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.lzy.okgo.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Response;

import static com.alibaba.sdk.android.oss.common.HttpMethod.GET;
import static com.chuanjiabao.wisdom.bean.Constants.REQUEST_CODE_COPYREASION;
import static com.chuanjiabao.wisdom.bean.Constants.REQUEST_CODE_USER_SEARCH;

public class SecondFragment extends BaseLazyFragment {

    FragmentSecondBinding binding;
    ReasionInfoCallbackBean.DataBean bean;
    boolean isShow = false, isFirst = true;
    private List<LocalMedia> selectList = new ArrayList<>();
    private CreateSecretAlbumDialog dialog;

    OSSClient oss;
    List<FamilyResCallbackBean.DataBeanX.DataBean> listDataSecond = new ArrayList<>();
    Map<String, List<FamilyResCallbackBean.DataBeanX.DataBean>> maps = new HashMap<>();
    List<ImageBean> listItemLocations = new ArrayList<>();
    List<ImageBean> listItemLocationsSecond = new ArrayList<>();
    List<String> months = new ArrayList<>();
    MonthAdapter monthAdapter;
    private int pageNum = 1;

    String homeId = "", peopleId = "", type = "", bucketName;
    List<String> fileIds = new ArrayList<>();
    List<String> fileIdsSecond = new ArrayList<>();

    //图片/视频/文本
    private String photoUrl = "", photoHint = "所有图片";
    private String videoUrl = "", videoHint = "所有视频";
    private String textUrl = "", textHint = "文本";

    @Override
    public int setLayoutId() {
        return R.layout.fragment_second;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(
                LayoutInflater.from(getActivity()),
                R.layout.fragment_second,
                container,
                false
        );
        binding.setFragment(this);
        return binding.getRoot();
    }

    @Override
    protected void onVisible() {
        isShow = false;
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int code = msg.what;
            switch (code) {
                case REQUEST_CODE_USER_SEARCH:
                    showShakeAnimation(binding.ivModuleSecretHint, -25);
                    break;
                case REQUEST_CODE_COPYREASION:
                    getSecretFileTotal();
                    break;
                default:
            }
        }
    };

    public void initRecycler() {
        monthAdapter = new MonthAdapter(getActivity(), months, maps, false, true);
        binding.recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.recycler.setItemAnimator(new DefaultItemAnimator());
        ((SimpleItemAnimator) binding.recycler.getItemAnimator()).setSupportsChangeAnimations(false);
        binding.recycler.setAdapter(monthAdapter);
        monthAdapter.setOnThirdClickListener((first, second, third, url) -> {
            if (!fileIds.contains(second + "")) {
                fileIds.add(second + "");
                listItemLocations.add(new ImageBean(first, second, third));
            } else {
                fileIdsSecond = fileIds;
                fileIdsSecond.remove(second + "");
                fileIds = fileIdsSecond;
                listItemLocationsSecond = listItemLocations;
                for (ImageBean iv : listItemLocations) {
                    if (iv.getFirst() == first && iv.getSecond() == second) {
                        listItemLocationsSecond.remove(iv);
                    }
                }
                listItemLocations = listItemLocationsSecond;
            }
        });

        binding.refreshLayout.setOnRefreshListener(refreshlayout -> {
            pageNum = 1;
            maps.clear();
            months.clear();
            getSecretFiles();
        });

        binding.refreshLayout.setOnLoadMoreListener(refreshlayout -> getSecretFiles());

        binding.refreshLayout.autoRefresh();
    }

    public void showAnimaition() {
        Runnable runnable = () -> {
            while (isShow) {
                SystemClock.sleep(1000);
                handler.sendEmptyMessage(REQUEST_CODE_USER_SEARCH);
            }
        };
        BHThreadPool.getInstance().executeTask(runnable);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void lazyLoad() {
        bean = (ReasionInfoCallbackBean.DataBean) SpUtils.getBean("module_reasion");
        if (0 == bean.getSet_secret()) {
            binding.viewBaseTitleBar.setVisibility(View.GONE);
            binding.tvModuleSecretHint.setVisibility(View.GONE);
            binding.flModuleAddSecret.setVisibility(View.GONE);
            dialog = new CreateSecretAlbumDialog(getActivity());
            dialog.show();
            dialog.setOnBHClickListener(new OnBHClickListener() {
                @Override
                public void onCloseClick() {
                    startActivity(new Intent(getActivity(), CreateSecretInputPwdActivity.class));
                }
            });
        } else {
            binding.viewBaseTitleBar.setVisibility(View.VISIBLE);
            binding.flModuleAddSecret.setVisibility(View.VISIBLE);

            if (oss == null) getAuth();
        }

        binding.refreshLayout.setOnRefreshListener(refreshlayout -> {
            pageNum = 1;
            maps.clear();
            months.clear();
            getSecretFiles();
        });

        binding.refreshLayout.setOnLoadMoreListener(refreshlayout -> getSecretFiles());

        binding.tvModuleAddSecret.setOnClickListener(this);
        binding.tvModuleCheck.setOnClickListener(this);
        binding.rightText.setOnClickListener(this);
        binding.rlModuleQucky.setOnClickListener(this);

        if (binding.flModuleAddSecret.getVisibility() == View.VISIBLE) {
            Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.secret_bottom_in);
            anim.setInterpolator(new DecelerateInterpolator());
            binding.flModuleAddSecret.startAnimation(anim);
            //noinspection ResultOfMethodCallIgnored
            Completable.timer(500, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(() -> {
                        Animation anim2 = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_anim_3);
                        anim2.setInterpolator(new DecelerateInterpolator());
                        binding.tvModuleAddSecret.startAnimation(anim2);
                    });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvModuleCheck:
                DropPopWindowUtils.showDrop(
                        getActivity(),
                        binding.tvModuleCheck,
                        photoUrl, videoUrl, textUrl, photoHint, videoHint, textHint,
                        this::allClick
                );
                break;
            case R.id.rlModuleQucky:
                MainActivity main = (MainActivity) getActivity();
                main.updatePersonResource(homeId, peopleId);
                RxPermissions permissions = new RxPermissions(getActivity());
                permissions.request(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA
                ).subscribe(new RxObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            startActivityForResult(new Intent(getActivity(), ShootActivity.class), 100);
                        } else {
                            ToastUtil.showToast("请开启读取权限");
                        }
                    }
                });
                break;
            case R.id.rightText:
                startActivity(new Intent(getActivity(), SecretResActivity.class));
                break;
            case R.id.tvModuleAddSecret:
                ThirdSelectDialog dialog = new ThirdSelectDialog(getActivity());
                dialog.setTitleText("视频/图片", "文本");
                dialog.show();
                dialog.setOnBHClickListener(new OnBHClickListener() {
                    @Override
                    public void onConfirmClick() {
                        startActivity(
                                new Intent(
                                        getActivity(),
                                        UpdateTextActivity.class
                                )
                                .putExtra("module_type", "secret")
                        );
                    }

                    @Override
                    public void onCloseClick() {
                        homeId = SpResourceUtil.getHomeId();
                        peopleId = SpResourceUtil.getUserId();
                        MainActivity mainActivity = (MainActivity) getActivity();
                        mainActivity.updatePersonResource(homeId, peopleId);
                        PictureSelector.create(getActivity())
                                .openGallery(PictureMimeType.ofAll())
                                .theme(R.style.picture_default_style)
                                .maxSelectNum(9)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .previewImage(true)
                                .previewVideo(true)
                                .enablePreviewAudio(true)
                                .isCamera(false)
                                .isZoomAnim(true)
                                .imageFormat(PictureMimeType.PNG)
                                .setOutputCameraPath("/CustomPath")
                                .enableCrop(false)
                                .compress(false)
                                .synOrAsy(true)
                                .glideOverride(160, 160)
                                .isGif(true)
                                .freeStyleCropEnabled(true)
                                .openClickSound(true)
                                .selectionMedia(selectList)
                                .withAspectRatio(3, 2)
                                .previewEggs(true)
                                .minimumCompressSize(100)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }
                });
                break;
        }
    }

    public void getAuth() {
        HTTPAPI.getInstance().getAuth(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s, false);
                } else {
                    final AuthCallbackBean bean = GsonUtil.GsonToBean(s, AuthCallbackBean.class);
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(
                                    bean.getData().getAccessKeyId(),
                                    bean.getData().getAccessKeySecret(),
                                    bean.getData().getSecurityToken()) {

                                @Override
                                public OSSFederationToken getFederationToken() {
                                    return super.getFederationToken();
                                }
                            };
                            OSSLog.enableLog();
                            oss = new OSSClient(getActivity(), "https://" + bean.getData().getEndPoint(),
                                    credentialProvider, FApplication.getInstance().getClientConfiguration());
                            handler.sendEmptyMessage(REQUEST_CODE_COPYREASION);
                        }
                    };
                    BHThreadPool.getInstance().executeTask(runnable);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

        bean = (ReasionInfoCallbackBean.DataBean) SpUtils.getBean("module_reasion");
        if (1 == bean.getSet_secret()) {
            binding.viewBaseTitleBar.setVisibility(View.VISIBLE);
            binding.flModuleAddSecret.setVisibility(View.VISIBLE);
            pageNum = 1;
            months.clear();
            maps.clear();
            getAuth();
        } else {
            if (hasVisible()) {
                binding.viewBaseTitleBar.setVisibility(View.GONE);
                binding.tvModuleSecretHint.setVisibility(View.GONE);
                binding.flModuleAddSecret.setVisibility(View.GONE);
                if (dialog == null) {
                    dialog = new CreateSecretAlbumDialog(getActivity());
                    dialog.show();
                    dialog.setOnBHClickListener(new OnBHClickListener() {
                        @Override
                        public void onCloseClick() {
                            startActivity(new Intent(getActivity(), CreateSecretInputPwdActivity.class));
                        }
                    });
                } else {
                    if (!dialog.isShowing()) dialog.show();
                }
            }
        }
    }

    public void allClick(String type) {
        pageNum = 1;
        maps.clear();
        months.clear();
        this.type = type;
        if (TextUtils.equals("0", type)) this.type = "";
        getSecretFiles();
    }

    //获取私密读取授权，读取相册内容
    public void getSecretFiles() {
        HTTPAPI.getInstance().getSecretFiles(pageNum + "", type, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                binding.refreshLayout.finishLoadMore();
                binding.refreshLayout.finishRefresh();
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    FamilyResCallbackBean listB = GsonUtil.GsonToBean(s, FamilyResCallbackBean.class);
                    listDataSecond = listB.getData().getData();
                    if (isFirst && listDataSecond.size() == 0) {
                        LogUtil.e("第一次进入");
                        isFirst = false;
                        showAnimaition();
                    } else {
                        if (listDataSecond.size() == 0) {
                            monthAdapter.notifyDataSetChanged();
                        } else {
                            pageNum++;
                            for (FamilyResCallbackBean.DataBeanX.DataBean dataBean : listDataSecond) {
                                String createTime = dataBean.getCreate_time();
                                String dateNow = TimeHelper.getInstance().getNowTime("yyyy年MM月dd日");
                                String m = TimeHelper.getInstance()
                                        .stringToString(
                                                "yyyy-MM-dd HH:mm:ss",
                                                "yyyy年MM月dd日",
                                                createTime
                                        );

                                if (TextUtils.equals(dateNow, m)) {
                                    m = "今天";
                                } else if (TextUtils.equals(
                                        dateNow.substring(0, 4),
                                        m.substring(0, 4)
                                )) {
                                    m = TimeHelper.getInstance()
                                            .stringToString(
                                                    "yyyy-MM-dd HH:mm:ss",
                                                    "M月dd日",
                                                    createTime
                                            );
                                }

                                bucketName = dataBean.getFile_bucket();
                                if (1 == dataBean.getFile_type()) {
                                    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                                            dataBean.getFile_bucket(),
                                            dataBean.getFile(),
                                            30 * 60,
                                            GET);
                                    Map<String, String> map = new HashMap<>();
                                    map.put("x-oss-process", dataBean.getParams().getXossprocess());
                                    map.put("test", dataBean.getParams().getTest());
                                    generatePresignedUrlRequest.setQueryParameter(map);
                                    try {
                                        String url = oss.presignConstrainedObjectURL(generatePresignedUrlRequest);

                                        if (TextUtils.isEmpty(photoUrl)) photoUrl = url;
                                        dataBean.setThum(url);
                                    } catch (ClientException e) {
                                        e.printStackTrace();
                                    }
                                } else if (2 == dataBean.getFile_type()) {
                                    try {
                                        String url = oss.presignConstrainedObjectURL(dataBean.getFile_bucket(),
                                                dataBean.getVideo_img(), 60 * 60);

                                        if (TextUtils.isEmpty(videoUrl)) videoUrl = url;
                                        dataBean.setThum(url);
                                    } catch (ClientException e) {
                                        e.printStackTrace();
                                    }
                                }

                                if (!months.contains(m)) {
                                    List<FamilyResCallbackBean.DataBeanX.DataBean> dataBeansList = new ArrayList<>();
                                    dataBeansList.add(dataBean);
                                    months.add(m);
                                    maps.put(m, dataBeansList);
                                } else {
                                    if (!maps.get(m).contains(dataBean)) {
                                        maps.get(m).add(dataBean);
                                    }
                                }
                            }
                            monthAdapter.notifyDataSetChanged();

                            if (maps.size() != 0) {
                                binding.ivModuleSecretHint.setVisibility(View.GONE);
                                binding.tvModuleSecretHint.setVisibility(View.GONE);
                                isShow = false;
                            } else {
                                binding.ivModuleSecretHint.setVisibility(View.VISIBLE);
                                binding.tvModuleSecretHint.setVisibility(View.VISIBLE);
                                isShow = true;
                                showAnimaition();
                            }
                        }
                    }
                }
            }
        });
    }

    private void showShakeAnimation(final View view, final int y) {
        if (y >= 0) {
            return;
        }
        TranslateAnimation anim = new TranslateAnimation(0,
                0, 0, y);
        anim.setInterpolator(new CycleInterpolator(1f));
        anim.setDuration(200);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                showShakeAnimation(view, y + 5);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(anim);
    }

    private void getSecretFileTotal() {
        HTTPAPI.getInstance().getSecretFileTotal(new StringCallback() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    FamilyFileTotalBean bean = GsonUtil.GsonToBean(s, FamilyFileTotalBean.class);
                    for (FamilyFileTotalBean.DataBean dataBean : bean.getData()) {
                        if (dataBean.getFile_type() == 1) {
                            photoHint = dataBean.getNum() + "";
                        } else if (2 == dataBean.getFile_type()) {
                            videoHint = dataBean.getNum() + "";
                        } else if (4 == dataBean.getFile_type()) {
                            textUrl = dataBean.getContent_intro();
                            textHint = dataBean.getNum() + "";
                        }
                    }

                    //初始化数据
                    initRecycler();
                }
            }
        });
    }

    private Boolean hasVisible() {
        return getUserVisibleHint() && isResumed();
    }

}
